﻿using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using T.ServiceComponent.DAC.Service;
using System.Reflection;
using System.Data;
using T.FAS.Runtime.Excel.Entity;
using T.ServiceComponent.DataAccessEx.Core;
using T.FAS.Runtime.Base.Common;

namespace T.FAS.Runtime.Excel.Dao
{
    public class ImportTaskDao : DaoService<ImportTask>
    {
        public override string TableName => "FAS_ImportTask";
        public override string IDColumnName => "ID";
        public ImportTaskDao() : base()
        {
            DBName = "TFAS";
        }
        public override List<string> ExceptColumnName => new List<string> { "ImportTime" };
        /// <summary>
        /// 根据MD5码查是否存在重复导入
        /// </summary>
        /// <param name="md5"></param>
        /// <returns></returns>
        public int CheckIsImportByMD5(string md5)
        {
            List<object> objects = base.GetObjectsByFilter($"FileMD5='{md5}'");
            if (objects == null)
            {
                return 0;
            }
            return objects.Count;
        }
        /// <summary>
        /// 根据文件查是否存在重复导入
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public int CheckIsImportByFileName(string cdoID, string userID, string fileName)
        {
            List<IDbDataParameter> paramList = new List<IDbDataParameter>();
            paramList.Add(DB.MakeInParam("@cdoID", TDbDataType.VarChar, cdoID));
            paramList.Add(DB.MakeInParam("@userID", TDbDataType.VarChar, userID));
            paramList.Add(DB.MakeInParam("@fileName", TDbDataType.VarChar, fileName));
            var sql = string.Format($@"select count(1) from {TableName} where cdoID=@cdoID and UserID=@userID and FileName=@fileName");
            int count;
            var result = DB.ExecuteScalar(sql, paramList.ToArray());
            if (int.TryParse(Convert.ToString(result), out count))
            {
                return count;
            }
            return 0;
        }
        /// <summary>
        /// 根据文件名称删除 单元测试用
        /// </summary>
        /// <returns></returns>
        public void DeleteByFileName(string fileName)
        {
            List<IDbDataParameter> paramList = new List<IDbDataParameter>();
            paramList.Add(DB.MakeInParam("@fileName", TDbDataType.VarChar, fileName));
            var sql = string.Format($@"delete from {TableName} where FileName=@fileName");
            DB.ExecSqlStatement(sql, paramList.ToArray());
        }
        /// <summary>
        /// 获取导入任务列表
        /// </summary>
        /// <param name="cdoID"></param>
        /// <returns></returns>
        public List<ImportTask> GetTaskList(string cdoID)
        {
            var result = new List<ImportTask>();
            List<IDbDataParameter> paramList = new List<IDbDataParameter>();
            paramList.Add(DB.MakeInParam("@cdoID", TDbDataType.VarChar, cdoID));
            var sql = string.Format($@"select * from {TableName} where CDOID=@cdoID;");
            var ds = DB.ExecuteDataSet(sql, paramList.ToArray());
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    var row = ds.Tables[0].Rows[i];
                    result.Add(ConvertToObject(Columns, row));
                }
            }
            return result;
        }
        /// <summary>
        /// 查询导入任务列表
        /// </summary>
        /// <returns></returns>
        public Dictionary<string, object> GetTaskList(string cdoID, Dictionary<string, string> filter)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            try
            {
                var result = new List<ImportTask>();
                List<IDbDataParameter> paramsList = new List<IDbDataParameter>();
                paramsList.Add(DB.MakeInParam("@cdoID", TDbDataType.VarChar, cdoID));
                string userID = UserUtil.GetCurrentUserID();
                var sql = $"SELECT * FROM {TableName} WHERE CDOID=@cdoID and UserID = '{userID}' ";
                var sql2 = $"SELECT 1 FROM {TableName} WHERE CDOID=@cdoID and UserID = '{userID}' ";
                if (filter != null && filter.ContainsKey("pageSize") && filter.ContainsKey("pageIndex"))
                {
                    int pageSize = int.Parse(filter["pageSize"]);
                    int pageIndex = int.Parse(filter["pageIndex"]);
                    int offset = (pageIndex - 1) * pageSize;
                    sql += $"Order by CreateTime desc limit @pageSize offset @offset";
                    paramsList.Add(DB.MakeInParam("@pageSize", TDbDataType.Int, pageSize));
                    paramsList.Add(DB.MakeInParam("@offset", TDbDataType.Int, offset));
                }
                var ds = DB.ExecuteDataSet(sql, paramsList.ToArray());
                var totalds = DB.ExecuteDataSet(sql2, paramsList.ToArray());
                if (ds != null && ds.Tables.Count > 0)
                {
                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        ImportTask task = ConvertToObject(base.Columns, row);
                        task.ImportTime = ToolUtil.GetDateDiff(task.CreateTime);
                        result.Add(task);
                    }
                }
                return ToolUtil.GetTaskList(dic, result, totalds);
            }
            catch (Exception e)
            {
                dic.Add("state", "0");
                dic.Add("errmsg", e.ToString());
                return dic;
            }
        }
        /// <summary>
        /// 获取过期任务列表
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public List<ImportTask> GetOutofdateTaskList(DateTime date)
        {
            var result = new List<ImportTask>();
            List<object> objects = base.GetObjectsByFilter($"CreateTime<='{date}'");
            if (objects != null)
            {
                objects.ForEach(obj => result.Add(obj as ImportTask));
            }
            return result;
        }
        /// <summary>
        /// 清空任务
        /// </summary>
        public void ClearTask(string userID, string cdoID)
        {
            List<IDbDataParameter> paramList = new List<IDbDataParameter>();
            paramList.Add(DB.MakeInParam("@cdoID", TDbDataType.VarChar, cdoID));
            paramList.Add(DB.MakeInParam("@userID", TDbDataType.VarChar, userID));
            DB.ExecSqlStatement($"delete from FAS_ImportTaskDetail where TaskID in (select ID from FAS_ImportTask where UserId =@userID and CDOID =@cdoID)", paramList.ToArray());
            DB.ExecSqlStatement($"delete from {TableName} where UserId =@userID and CDOID =@cdoID", paramList.ToArray());
        }
    }
}
